using System;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model.Bom;

namespace WPF_MVVM_Test.Services.Bom
{
    /// <summary>
    /// BOM组成服务类
    /// </summary>
    public class BomCompositionService
    {
        private readonly HttpClient _httpClient;
        private readonly string _baseUrl = "http://8.140.242.140:8888/api/ProductionPlans";

        public BomCompositionService()
        {
            _httpClient = new HttpClient();
        }

        /// <summary>
        /// 根据BOM ID获取BOM树形结构
        /// </summary>
        /// <param name="bomId">BOM ID</param>
        /// <returns></returns>
        public async Task<BomCompositionApiResponse> GetBomTreeAsync(string bomId)
        {
            try
            {
                var url = $"{_baseUrl}/bom-tree/{bomId}";

                System.Diagnostics.Debug.WriteLine($"请求BOM组成数据，URL: {url}");

                var response = await _httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();

                    System.Diagnostics.Debug.WriteLine($"BOM组成API响应: {jsonString}");

                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true,
                        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                        UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip
                    };

                    var result = JsonSerializer.Deserialize<BomCompositionApiResponse>(jsonString, options);

                    if (result != null)
                    {
                        System.Diagnostics.Debug.WriteLine($"BOM组成数据解析成功，数据数量: {result.Data?.Count ?? 0}");
                        return result;
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("BOM组成数据解析失败，返回空结果");
                        return new BomCompositionApiResponse
                        {
                            IsSuc = false,
                            Code = 500,
                            Msg = "数据解析失败"
                        };
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"BOM组成API请求失败，状态码: {response.StatusCode}");
                    return new BomCompositionApiResponse
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"请求失败: {response.StatusCode}"
                    };
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"BOM组成API请求异常: {ex.Message}");
                return new BomCompositionApiResponse
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"请求异常: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}